import EmitterEvent from "./EmitterEvent";
import IEmitterListen from "./IEmitterListen";

export default class EmitterTarget {
  public listenList: IEmitterListen = {};
  constructor() {}
  // 侦听
  public addEventListener(type: string, listen: Function): void {
    if (!this.listenList[type]) this.listenList[type] = [];
    this.listenList[type].push(listen);
  }
  // 移除
  public removeEventListener(type: string, listen: Function): void {
    if (!this.listenList[type]) return;
    let index: number = this.listenList[type].indexOf(listen);
    if (index > -1) {
      this.listenList[type].splice(index, 1);
    }
  }
  // 抛发
  public dispatchEvent(evt: EmitterEvent): boolean {
    let list: Array<Function> = this.listenList[evt.type];
    if (!list) return false;
    evt.currentTarget = this;
    evt.target = this;
    for (let i: number = 0; i < list.length; i++) {
      list[i].call(this, evt); //执行当前type的所有回调
    }
    return true;
  }
}
